import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

/*
 * FriendsList.java
 *
 * Created on Apr 11, 2012, 10:21:58 AM
 */

/**
 *
 * @author oberliat
 */
public class FriendsList extends javax.swing.JPanel {
    private DatabaseConnection dbConnect;
    private Controller controls;
    /** Creates new form FriendsList */
    public FriendsList(Controller control, DatabaseConnection db) {
        initComponents();
        dbConnect = db;
        controls = control;
    }
    /**
        Finds all of this persons friends with a similar name to <searchStr>
        and adds a Friend Panel for each one. Also, clears the current 
        scrollPane of all of its current panels  
    **/
    public void searchFriends(String searchStr) {
        this.friendsRightContainer.removeAll();
        this.friendsLeftContainer.removeAll();
        /*String friendsQuery = String.format(
            "SELECT u.username AS username, u.email AS email FROM user u, "
                + "friends f WHERE u.username = f.user2 AND f.user1 = '%s' "
                + "AND f.user2 LIKE '%%%s%%'", 
            controls.username, searchStr
        );*/ 
        
        String friendsQuery = String.format(
            "SELECT u.username AS username, u.email AS email FROM user u, friends f WHERE "
                + "u.username = f.user2 AND f.user1 = '%s' AND u.username LIKE '%%%s%%'", 
            controls.username, searchStr
        );
        
        System.out.println(friendsQuery);
        
        String newFriendsQuery = String.format(
            "SELECT u.username AS username, u.email AS email FROM user u WHERE "
                + "u.username NOT IN(SELECT f.user2 FROM friends f WHERE user1='%s') "
                + "AND u.username != '%s' AND u.username LIKE '%%%s%%'", 
            controls.username, controls.username, searchStr
        ); 
        
        dbConnect.connect();
        
        ResultSet newFriends = dbConnect.executeQuery(newFriendsQuery);
        ResultSet friends = dbConnect.executeQuery(friendsQuery);
        if (friends != null) {
            String friendUsername;
            String friendEmail;
            //friendsScrollPane.setLayout(new java.awt.BorderLayout());
            try {
                ArrayList<FriendPanel> panels = new ArrayList();
                int i = 0;
                while(friends.next()) {
                    friendUsername = friends.getString("username");
                    friendEmail = friends.getString("email");
                    FriendPanel panel = new FriendPanel(this.controls, this.dbConnect);
                    panel.setUsername(friendUsername);
                    panel.setEmail(friendEmail);
                    friendsLeftContainer.add(panel);
                    panels.add(panel);
                    i++;
                }
            }    
            catch (SQLException e) {
                System.err.println("Problem traversing through friends");
            }
        }
        
        if (newFriends != null) {
            String newFriendUsername;
            String newFriendEmail;
            //friendsScrollPane.setLayout(new java.awt.BorderLayout());
            try {
                ArrayList<FriendPanel> panels = new ArrayList();
                int i = 0;
                while(newFriends.next()) {
                    newFriendUsername = newFriends.getString("username");
                    newFriendEmail = newFriends.getString("email");
                    FriendPanel panel = new FriendPanel(this.controls, this.dbConnect);
                    panel.setUsername(newFriendUsername);
                    panel.setEmail(newFriendEmail);
                    panel.notFriend();
                    friendsRightContainer.add(panel);
                    panels.add(panel);
                    i++;
                }
            }    
            catch (SQLException e) {
                System.err.println("Problem traversing through friends");
            }
        }
        this.validate();
        this.repaint();
                
        dbConnect.closeConnection();
        
        
    }
    
    /**
        Finds all of this persons friends and adds a Friend Panel for each one
        Also, clears the current scrollPane of all of its current panels  
    **/
    public void addFriends() {
        this.friendsRightContainer.removeAll();
        this.friendsLeftContainer.removeAll();
        String friendsQuery = String.format(
            "SELECT u.username AS username, u.email AS email FROM user u, friends f WHERE "
                + "u.username = f.user2 AND f.user1 = '%s'", 
            controls.username
        );
        
        ResultSet friends = dbConnect.executeQuery(friendsQuery);
        if (friends != null) {
            String friendUsername;
            String friendEmail;
            //friendsScrollPane.setLayout(new java.awt.BorderLayout());
            try {
                ArrayList<FriendPanel> panels = new ArrayList();
                int i = 0;
                while(friends.next()) {
                    friendUsername = friends.getString("username");
                    friendEmail = friends.getString("email");
                    FriendPanel panel = new FriendPanel(this.controls, this.dbConnect);
                    panel.setUsername(friendUsername);
                    panel.setEmail(friendEmail);
                    if (i % 2 == 0) {
                        friendsRightContainer.add(panel);
                    }
                    else {
                        friendsLeftContainer.add(panel);
                    }
                    panels.add(panel);
                    i++;
                }
                this.validate();
                this.repaint();
            }    
            catch (SQLException e) {
                System.err.println("Problem traversing through friends");
            }
            finally {
                dbConnect.closeConnection();
            }
        }
        else {
            System.out.println(controls.username + " has no friends");
        }
    }
    
    /**
       This methods removes a panel from this component and repaints 
    **/
    public void deletePanel(javax.swing.JPanel panel) {
        this.friendsLeftContainer.remove(panel);
        this.friendsRightContainer.remove(panel);
        this.friendsRightContainer.validate();
        this.friendsRightContainer.repaint();
        this.friendsLeftContainer.validate();
        this.friendsLeftContainer.repaint();
    }

    void updateVisibility(int vis){
        String update = "UPDATE user SET visibility = " + vis + " WHERE username = '" + controls.username + "';";
        int result = dbConnect.executeUpdate(update);
        if(result != -1)
            System.out.println("Visibility changes saved");
        else
            System.out.println("Could not save visibility changes to the database.");
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        bannerPanel = new javax.swing.JPanel();
        bannerLabel = new javax.swing.JLabel();
        friendSearchInput = new javax.swing.JTextField();
        friendSearchButton = new javax.swing.JButton();
        backToProfileButton = new javax.swing.JButton();
        friendRequestsButton = new javax.swing.JButton();
        showFriendsButton = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        allUsersButton = new javax.swing.JButton();
        friendsOnlyButton = new javax.swing.JButton();
        noOneButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        friendsScrollPane = new javax.swing.JPanel();
        friendsRightContainer = new javax.swing.JPanel();
        friendsLeftContainer = new javax.swing.JPanel();

        setBackground(new java.awt.Color(249, 249, 252));
        setPreferredSize(new java.awt.Dimension(800, 650));
        setRequestFocusEnabled(false);

        bannerPanel.setBackground(new java.awt.Color(249, 249, 252));
        bannerPanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        bannerLabel.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
        bannerLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/draw-something-logo.jpg"))); // NOI18N
        bannerLabel.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

        friendSearchInput.setText("Search All Users");

        friendSearchButton.setBackground(new java.awt.Color(0, 102, 153));
        friendSearchButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/search.png"))); // NOI18N
        friendSearchButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                friendSearchButtonActionPerformed(evt);
            }
        });

        backToProfileButton.setText("Back to Profile");
        backToProfileButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                backToProfileButtonActionPerformed(evt);
            }
        });

        friendRequestsButton.setText("Friend Requests");
        friendRequestsButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                friendRequestsButtonActionPerformed(evt);
            }
        });

        showFriendsButton.setText("Show Friends");
        showFriendsButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                showFriendsButtonActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel1.setText("                       Set my stats visible to:");

        allUsersButton.setText("All users");
        allUsersButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                allUsersButtonMouseClicked(evt);
            }
        });

        friendsOnlyButton.setText("Friends only");
        friendsOnlyButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                friendsOnlyButtonMouseClicked(evt);
            }
        });

        noOneButton.setText("No one");
        noOneButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                noOneButtonMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout bannerPanelLayout = new javax.swing.GroupLayout(bannerPanel);
        bannerPanel.setLayout(bannerPanelLayout);
        bannerPanelLayout.setHorizontalGroup(
            bannerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(bannerPanelLayout.createSequentialGroup()
                .addComponent(bannerLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 424, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(bannerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(backToProfileButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(friendRequestsButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(showFriendsButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(bannerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, bannerPanelLayout.createSequentialGroup()
                        .addComponent(friendSearchInput, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(friendSearchButton, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(52, 52, 52))
                    .addGroup(bannerPanelLayout.createSequentialGroup()
                        .addComponent(allUsersButton)
                        .addGap(18, 18, 18)
                        .addComponent(friendsOnlyButton)
                        .addGap(18, 18, 18)
                        .addComponent(noOneButton)
                        .addGap(16, 16, 16))
                    .addGroup(bannerPanelLayout.createSequentialGroup()
                        .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 273, Short.MAX_VALUE)
                        .addContainerGap())))
        );
        bannerPanelLayout.setVerticalGroup(
            bannerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(bannerLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGroup(bannerPanelLayout.createSequentialGroup()
                .addGroup(bannerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(backToProfileButton)
                    .addComponent(friendSearchInput, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(friendSearchButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(bannerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(bannerPanelLayout.createSequentialGroup()
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(bannerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(allUsersButton)
                            .addComponent(friendsOnlyButton)
                            .addComponent(noOneButton)))
                    .addGroup(bannerPanelLayout.createSequentialGroup()
                        .addComponent(friendRequestsButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(showFriendsButton))))
        );

        jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

        friendsScrollPane.setAutoscrolls(true);

        friendsRightContainer.setAutoscrolls(true);
        friendsRightContainer.setPreferredSize(new java.awt.Dimension(360, 547));
        friendsRightContainer.setVerifyInputWhenFocusTarget(false);
        friendsRightContainer.setLayout(new javax.swing.BoxLayout(friendsRightContainer, javax.swing.BoxLayout.Y_AXIS));

        friendsLeftContainer.setAutoscrolls(true);
        friendsLeftContainer.setLayout(new javax.swing.BoxLayout(friendsLeftContainer, javax.swing.BoxLayout.Y_AXIS));

        javax.swing.GroupLayout friendsScrollPaneLayout = new javax.swing.GroupLayout(friendsScrollPane);
        friendsScrollPane.setLayout(friendsScrollPaneLayout);
        friendsScrollPaneLayout.setHorizontalGroup(
            friendsScrollPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(friendsScrollPaneLayout.createSequentialGroup()
                .addComponent(friendsRightContainer, javax.swing.GroupLayout.DEFAULT_SIZE, 388, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(friendsLeftContainer, javax.swing.GroupLayout.PREFERRED_SIZE, 358, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(110, 110, 110))
        );
        friendsScrollPaneLayout.setVerticalGroup(
            friendsScrollPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(friendsScrollPaneLayout.createSequentialGroup()
                .addComponent(friendsRightContainer, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap(12, Short.MAX_VALUE))
            .addGroup(friendsScrollPaneLayout.createSequentialGroup()
                .addComponent(friendsLeftContainer, javax.swing.GroupLayout.DEFAULT_SIZE, 548, Short.MAX_VALUE)
                .addContainerGap())
        );

        jScrollPane1.setViewportView(friendsScrollPane);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 830, Short.MAX_VALUE)
            .addComponent(bannerPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(bannerPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(17, 17, 17)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 550, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void backToProfileButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backToProfileButtonActionPerformed
        this.controls.openProfile();
    }//GEN-LAST:event_backToProfileButtonActionPerformed

    private void friendSearchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_friendSearchButtonActionPerformed
        String searchStr = this.friendSearchInput.getText();
        if (!searchStr.equals("")) {
            this.searchFriends(searchStr);
        }
    }//GEN-LAST:event_friendSearchButtonActionPerformed

    private void showFriendsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_showFriendsButtonActionPerformed
        this.addFriends();
    }//GEN-LAST:event_showFriendsButtonActionPerformed

    private void friendRequestsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_friendRequestsButtonActionPerformed
        this.friendsRightContainer.removeAll();
        this.friendsLeftContainer.removeAll();
        String friendsQuery = String.format(
            "SELECT u.username AS username, u.email AS email FROM user u, friend_request f WHERE "
                + "u.username = f.user1 AND f.user_requested = '%s'", 
            controls.username
        );
        
        ResultSet friends = dbConnect.executeQuery(friendsQuery);
        if (friends != null) {
            String friendUsername;
            String friendEmail;
            //friendsScrollPane.setLayout(new java.awt.BorderLayout());
            try {
                ArrayList<FriendPanel> panels = new ArrayList();
                int i = 0;
                while(friends.next()) {
                    friendUsername = friends.getString("username");
                    friendEmail = friends.getString("email");
                    FriendPanel panel = new FriendPanel(this.controls, this.dbConnect);
                    panel.setUsername(friendUsername);
                    panel.setEmail(friendEmail);
                    panel.friendRequest();
                    if (i % 2 == 0) {
                        friendsRightContainer.add(panel);
                    }
                    else {
                        friendsLeftContainer.add(panel);
                    }
                    panels.add(panel);
                    i++;
                }
                this.validate();
                this.repaint();
            }    
            catch (SQLException e) {
                System.err.println("Problem traversing through friends");
            }
            finally {
                dbConnect.closeConnection();
            }
        }
        else {
            System.out.println(controls.username + " has no friends");
        }
    }//GEN-LAST:event_friendRequestsButtonActionPerformed

    private void allUsersButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_allUsersButtonMouseClicked
        updateVisibility(2);
    }//GEN-LAST:event_allUsersButtonMouseClicked

    private void friendsOnlyButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_friendsOnlyButtonMouseClicked
        updateVisibility(1);
    }//GEN-LAST:event_friendsOnlyButtonMouseClicked

    private void noOneButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_noOneButtonMouseClicked
        updateVisibility(0);
    }//GEN-LAST:event_noOneButtonMouseClicked


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton allUsersButton;
    private javax.swing.JButton backToProfileButton;
    private javax.swing.JLabel bannerLabel;
    private javax.swing.JPanel bannerPanel;
    private javax.swing.JButton friendRequestsButton;
    private javax.swing.JButton friendSearchButton;
    private javax.swing.JTextField friendSearchInput;
    private javax.swing.JPanel friendsLeftContainer;
    private javax.swing.JButton friendsOnlyButton;
    private javax.swing.JPanel friendsRightContainer;
    private javax.swing.JPanel friendsScrollPane;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton noOneButton;
    private javax.swing.JButton showFriendsButton;
    // End of variables declaration//GEN-END:variables

}
